<?php
session_start();
if (!isset($_SESSION['authenticated']) || !$_SESSION['authenticated']) {
    header('Location: auth.php'); // 如果未登录，重定向到登录页面
    exit();
}
?>

<?php
$dbFile = '../cms.db';
$pdo = new PDO('sqlite:' . $dbFile);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = $_POST['title'];
    $content = $_POST['content'];
    $id = $_POST['id'];

    $stmt = $pdo->prepare("UPDATE posts SET title = ?, content = ? WHERE id = ?");
    $stmt->execute([$title, $content, $id]);
    header("Location: index.php");
}

$post = $pdo->prepare("SELECT * FROM posts WHERE id = ?");
$post->execute([$_GET['id']]);
$postData = $post->fetch(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>编辑文章</title>
<link rel="shortcut icon" href="http://tc.gobghui.icu/uploads/66aefd85f0edc.png">
	<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no">
    <link rel="stylesheet" href="../css/mdui.min.css">
</head>
<body class="mdui-theme-primary-blue mdui-theme-accent-blue">
    <div class="mdui-container">
        <h1>编辑文章</h1>
        <form method="POST">
            <input type="hidden" name="id" value="<?php echo $postData['id']; ?>">
            <div class="mdui-textfield">
                <label class="mdui-textfield-label">标题</label>
                <input class="mdui-textfield-input" type="text" name="title" value="<?php echo htmlspecialchars($postData['title']); ?>" required>
            </div>
            <div class="mdui-textfield">
                <label class="mdui-textfield-label">内容</label>
                <textarea class="mdui-textfield-input" name="content" required><?php echo htmlspecialchars($postData['content']); ?></textarea>
            </div>
            <button class="mdui-btn mdui-btn-raised" type="submit">更新文章</button>
        </form>
    </div>
    <script src="../js/mdui.min.js"></script>
</body>
</html>
